import pymysql
from contextlib import contextmanager
from pprint import pprint


class DBUtil:
    def __init__(self, host, user, password, database="kejiyinhangyewuguanli", port=3306):
        self.config = {
            "host": host,
            "user": user,
            "password": password,
            "port": port,
            "database": database,
            "charset": "utf8mb4",
            "cursorclass": pymysql.cursors.DictCursor,
        }

    @contextmanager
    def get_cursor(self):
        """上下文管理器：自动关闭连接和游标"""
        conn = pymysql.connect(**self.config)
        cursor = conn.cursor()
        try:
            yield cursor
            conn.commit()
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            cursor.close()
            conn.close()

    def query(self, sql):
        """执行 SELECT 查询"""
        with self.get_cursor() as cursor:
            cursor.execute(sql)
            return cursor.fetchall()

    def execute(self, sql):
        """执行 INSERT / UPDATE / DELETE"""
        with self.get_cursor() as cursor:
            cursor.execute(sql)


if __name__ == '__main__':
    db = DBUtil(host='192.168.239.129', user='root', password='123456')
    sql = '''
    SELECT * FROM licaicanpin_goumai 
    WHERE licaicanpin_goumai_uuid_number = "f6793e6b-bf06-11f0-841d-58020551f15d"
    '''
    result = db.query(sql)
    pprint(result)
